package com.github.llyb120.config;

import com.github.llyb120.json.Arr;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import static com.github.llyb120.config.Result.fail;
import static com.github.llyb120.json.Json.a;

/**
 * @Author: Administrator
 * @Date: 2020/8/2 13:38
 */
@ControllerAdvice
public class ResponseResult implements ResponseBodyAdvice {


    @Override
    public Object beforeBodyWrite(Object resBody, MethodParameter arg1, MediaType arg2, Class arg3, ServerHttpRequest req,
                                  ServerHttpResponse res) {
        //resBody就是controller方法中返回的值，对其进行修改后再return就可以了
        if(resBody instanceof byte[] || resBody instanceof HttpEntity){
            return resBody;
        }
        if(!(resBody instanceof Result)){
            resBody = Result.ok(resBody);
        }
        return resBody;
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
//        return new ResponseEntity(Json.stringify(resBody), headers, HttpStatus.OK);
    }

    @Override
    public boolean supports(MethodParameter arg0, Class arg1) {
        //这里直接返回true,表示对任何handler的responsebody都调用beforeBodyWrite方法
        return !HttpEntity.class.isAssignableFrom(arg0.getMethod().getReturnType() );
    }

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Object test(Throwable throwable){
        throwable.printStackTrace();
        if(throwable instanceof MethodArgumentNotValidException){
            Arr<String> errs = a();
            for (FieldError fieldError : ((MethodArgumentNotValidException) throwable).getBindingResult().getFieldErrors()) {
                errs.add(fieldError.getDefaultMessage());
            }
            return fail(errs.join("\n"));
        } else if(throwable instanceof RuntimeException){
            return fail(throwable.getMessage());
        }
        return fail("服务器开了小差");
    }

}
